﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;

namespace Enter.Admin.Utils
{
    public static class SessionExtensions
    {
        // 其它地方获取Sessionhttps://blog.csdn.net/zhao277949522/article/details/91860409
        public static void Set<T>(this ISession session, string key, T value)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                key = typeof(T).Name;
            }
            session.SetString(key, Jsons.Serialize(value));
        }

        public static void Set<T>(this ISession session, T value)
        {
            session.Set<T>(typeof(T).Name, value);
        }

        public static T Get<T>(this ISession session, string key = "")
        {
            if (string.IsNullOrWhiteSpace(key)) 
            {
                key = typeof(T).Name;
            }
            var value = session.GetString(key);
            return value == null ? default : Jsons.Deserialize<T>(value);
        }

        // HttpContext.Response
        public static void SetCookies<T>(this HttpResponse response, string key, T value,int hours = 10)
        {
            if (EqualityComparer<T>.Default.Equals(value, default(T)))
            {
                response.Cookies.Delete(key);
            }
            else 
            {
                response.Cookies.Append(key, Jsons.Serialize(value), new CookieOptions
                {
                    Expires = DateTime.Now.AddHours(hours)
                });
            }
            
        }

        // HttpContext.Request
        public static T GetCookies<T>(this HttpRequest request, string key)
        {
            request.Cookies.TryGetValue(key, out string value);
            return string.IsNullOrEmpty(value) ? default : Jsons.Deserialize<T>(value);
        }


        public static bool IsAjax(this HttpRequest request)
        {
            bool result = false;
            // X-Requested-With
            var xreq = request.Headers.ContainsKey("X-Requested-With");
            if (xreq)
            {
                result = request.Headers["X-Requested-With"] == "XMLHttpRequest";
            }
            return result;
        }
    }
}
